//
//  GuangChiViewController.m
//  ShiWuPai
//
//  Created by app on 16/11/22.
//  Copyright © 2016年 QQ:244987427. All rights reserved.
//

#import "GuangChiViewController.h"

#import "UIView+Addition.h"
#import <Masonry.h>

#import "WHTitleCategory.h"

#import "BaseNetworkRequest.h"
#import "BaseNetworkRequest+GetGuangChiFeedCategory.h"
#import "HomePageViewController.h"
#import "EvaluatingViewController.h"
#import "KnowledgeViewController.h"
#import "CateViewController.h"

#define GetViewWidth(theView) CGRectGetWidth(theView.bounds)
#define GetViewHeight(theView) CGRectGetHeight(theView.bounds)
@interface GuangChiViewController ()<UIScrollViewDelegate>
@property (nonatomic, strong) UIBarButtonItem *rightItem;
@property (nonatomic, assign) NSUInteger buttontTitleCount;
@property (nonatomic, strong) NSMutableArray *scrollButtonArray;

@property (nonatomic,strong) UIScrollView *segmentScrollView;
@property (nonatomic,strong) UIScrollView *contentScrollView;
@property (nonatomic,strong) UIButton *selectButton;
@property (nonatomic,strong) UIView *dotView;
@end

@implementation GuangChiViewController

#pragma life cycle(生命周期)
- (void)viewDidLoad{
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem = self.rightItem;
    self.navigationItem.title = @"逛吃";
    
    self.automaticallyAdjustsScrollViewInsets=NO;
    [self addChildViewControllers];
    [self addSubViews];
    [self addConstraint];
    [self requestFeedCategorys];
    [self.contentScrollView addSubview:self.childViewControllers[0].view];
    self.childViewControllers[0].view.frame=self.contentScrollView.bounds;
    
    
    
}

- (UIBarButtonItem *)rightItem {
    if (!_rightItem) {
        _rightItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"ic_feed_camera_20x20_@2x.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(takePhoto)];
        
    }
    return _rightItem;
}


#pragma mark - UIScrollViewDelegate (ScrollView协议方法)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if ([scrollView isEqual:self.contentScrollView]) {
        CGFloat dx=scrollView.contentOffset.x;
        //上下联动
        if (dx>=0 && dx<=(self.scrollButtonArray.count-1)*GetViewWidth(self.view)) {
            
            float Multiple=dx/self.contentScrollView.contentSize.width;
            
            [self updateDotViewConstraintWithOffect:Multiple*self.segmentScrollView.contentSize.width+GetViewWidth(self.view)/8];
        }
        
    }
}

//获取scrollView滑动停止时偏移量
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if ([scrollView isEqual:self.contentScrollView]) {
        CGFloat dx=scrollView.contentOffset.x;
        // NSLog(@"dx:%f",dx);
        int indext=dx/GetViewWidth(self.contentScrollView);
        NSLog(@"indext:%d",indext);
        //改变上方button颜色
        [self changeButtonTextColorWithIndext:indext];
    }
}

#pragma mark - private methods(私有方法)
-(void)addChildViewControllers{
    HomePageViewController *homePageViewController=[[HomePageViewController alloc] init];
    [self addChildViewController:homePageViewController];
    
    EvaluatingViewController *evaluatingViewController=[[EvaluatingViewController alloc] init];
    [self addChildViewController:evaluatingViewController];
    
    KnowledgeViewController *knowledgeViewController=[[KnowledgeViewController alloc] init];
    [self addChildViewController:knowledgeViewController];
    
    CateViewController *cateViewController=[[CateViewController alloc] init];
    [self addChildViewController:cateViewController];
}

//向ScrollView中添加button以及button下面的小圆点
-(void)addScrollButtonsWithTitleArray:(NSArray *)titleArray{
    //设置
    //设置segmentScrollView的contentSize
    self.segmentScrollView.contentSize=CGSizeMake(GetViewWidth(self.view)*(titleArray.count)/4, 50);
    self.contentScrollView.contentSize=CGSizeMake(GetViewWidth(self.view)*(titleArray.count), GetViewHeight(self.contentScrollView));
    //button
    UIButton *lastButton=nil;
    for (int i=0; i<titleArray.count; i++) {
        //初始化，设置button
        UIButton *scrollButton=[UIButton buttonWithType:UIButtonTypeCustom];
        [self.scrollButtonArray addObject:scrollButton];
        scrollButton.tag=i+1;
        [scrollButton setTitle:titleArray[i] forState:UIControlStateNormal];
        [scrollButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [scrollButton setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        [scrollButton addTarget:self action:@selector(scrollButtonPress:) forControlEvents:UIControlEventTouchUpInside];
        [self.segmentScrollView addSubview:scrollButton];
        // scrollButton.backgroundColor=[UIColor blueColor];
        if (i==0) {
            scrollButton.selected=YES;
            self.selectButton=scrollButton;
        }
        
        //给button添加约束
        [scrollButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(GetViewWidth(self.view)/4, 40));
            make.top.equalTo(self.segmentScrollView.mas_top).offset(5);
            if (lastButton) {
                make.left.equalTo(lastButton.mas_right);
            }
            else{
                make.left.equalTo(self.segmentScrollView);
            }
        }];
        lastButton=scrollButton;
    }
    
    //圆点
    self.dotView=[[UIView alloc] init];
    self.dotView.backgroundColor=[UIColor redColor];
    self.dotView.layer.cornerRadius=2.5;
    [self.segmentScrollView addSubview:self.dotView];
    [self.dotView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(5);
        make.top.equalTo(self.selectButton.mas_bottom).offset(-5);
        make.left.equalTo(self.contentScrollView).offset(GetViewWidth(self.view)/8);
    }];
    
}

-(void)contentScroolViewAddSubViews{
    for (int i=0; i<self.childViewControllers.count; i++) {
        UIView *view=self.childViewControllers[i].view;
        view.frame=CGRectMake(i*GetViewWidth(self.view), 0, GetViewWidth(self.contentScrollView), GetViewHeight(self.contentScrollView));
        [self.contentScrollView addSubview:view];
    }
}
-(void)changeButtonTextColorWithIndext:(int)indext{
    self.selectButton.selected=NO;
    UIButton *button=self.scrollButtonArray[indext];
    button.selected=YES;
    self.selectButton=button;
    
}
-(void)updateDotViewConstraintWithIndext:(NSInteger)indext{
    
    
    [self.dotView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(5);
        make.top.equalTo(self.selectButton.mas_bottom).offset(-5);
        make.left.equalTo(self.contentScrollView).offset(GetViewWidth(self.view)/8*(indext*2-1));
    }];
    [UIView animateWithDuration:.5 animations:^{
        [self.view layoutIfNeeded];
    }];
    
    self.contentScrollView.contentOffset=CGPointMake(GetViewWidth(self.view)*(indext-1), 0);
    
}

-(void)updateDotViewConstraintWithOffect:(CGFloat)Offset{
    [self.dotView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(5);
        make.top.equalTo(self.selectButton.mas_bottom).offset(-5);
        make.left.equalTo(self.contentScrollView).offset(Offset);
    }];
    
    [self.view layoutIfNeeded];
    
}

#pragma mark - event response(事件响应)

- (void)takePhoto{
    
    
}

-(void)scrollButtonPress:(UIButton *)btn{
    if (self.selectButton.tag==btn.tag) {
        return;
    }
    
    else{
        self.selectButton.selected=NO;
        btn.selected=YES;
        self.selectButton=btn;
        
        //修改圆点的约束
        [self updateDotViewConstraintWithIndext:self.selectButton.tag];
        
        
    }
}

#pragma mark - network request(网络请求)
-(void)requestFeedCategorys{
    [BaseNetworkRequest getGuangChiFeedCategorySuccess:^(WHTitleCategory *titleCategory, NSError *error) {
        if (!error) {
            NSMutableArray *titleArray=[NSMutableArray array];
            for (WHCategory *category in titleCategory.categories) {
                [titleArray addObject:category.name];
            }
            //收到数据，上方segmentScrollView中添加button
            [self addScrollButtonsWithTitleArray:titleArray];
            
            //收到数据后，contentScroolView中开始添加视图控制器的view
            [self contentScroolViewAddSubViews];
        }
        
        else{
            //弹出错误提示框
        }
    }];
}
#pragma mark - init views(初始化子视图)
//添加子视图
-(void)addSubViews{
    //contentView
    self.contentScrollView=[[UIScrollView alloc] init];
    self.contentScrollView.pagingEnabled=YES;
    self.contentScrollView.delegate=self;
    self.contentScrollView.showsVerticalScrollIndicator=NO;
    self.contentScrollView.showsHorizontalScrollIndicator=NO;
    [self.view addSubview:self.contentScrollView];
    //   self.contentScrollView.backgroundColor=[UIColor purpleColor];
    
    
    //scrollView
    self.segmentScrollView=[[UIScrollView alloc] init];
    //
    //self.segmentScrollView.backgroundColor=[UIColor yellowColor];
    self.segmentScrollView.pagingEnabled=YES;
    [self.view addSubview:self.segmentScrollView];
    
    
}
//添加约束
-(void)addConstraint{
    //contentScrollView约束
    [self.contentScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(64+50);
        make.bottom.equalTo(self.view).offset(-49);
        make.width.left.equalTo(self.view);
    }];
    //segmentScrollView约束
    [self.segmentScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(64);
        make.width.left.equalTo(self.view);
        make.height.mas_equalTo(50);
    }];
    
}

#pragma mark - setter getter
-(NSMutableArray *)scrollButtonArray{
    if (!_scrollButtonArray) {
        _scrollButtonArray=[NSMutableArray array];
    }
    return _scrollButtonArray;
}
@end
